package cool.taomu.box.netty

import cool.taomu.box.netty.inter.IServerConfigure
import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelOption
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import javax.inject.Inject
import javax.inject.Named

class NettyServer {
	@Inject
	@Named("host")
	String host;

	@Inject
	@Named("port")
	int port;

	@Inject
	def void start(IServerConfigure config) {
		val coreNumber = Runtime.getRuntime().availableProcessors;
		val selectGroup = new NioEventLoopGroup(coreNumber);
		val ioGroup = new NioEventLoopGroup(coreNumber * 2);

		Runtime.runtime.addShutdownHook(new Thread() {
			override run() {
				selectGroup.shutdownGracefully();
				ioGroup.shutdownGracefully();
			}
		});

		var serverBootstrap = new ServerBootstrap();
		var bootstrap = serverBootstrap.group(selectGroup, ioGroup);
		bootstrap = bootstrap.channel(NioServerSocketChannel);
		bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
		config.bootstrap(bootstrap);
		bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
			override protected initChannel(SocketChannel ch) throws Exception {
				config.pipeline(ch.pipeline(), ch);
			}
		})
		bootstrap.bind(host, port).sync();
	}
}
